package com.ch.websocketdemo.socket;

import javax.websocket.Session;

/**
 * webSocket工具类
 *
 * @author CH
 * @data 2022/1/14
 */
public class WebSocketUtil {
    public static void sendMessage(Session session, String message) {
        if (session != null) {
            session.getAsyncRemote().sendText(message);
        }
    }

    public static void sendMessageObject(Session session, Object object) {
        if (session != null) {
            session.getAsyncRemote().sendObject(object);
        }
    }

    /**
     * 根据token发送消息
     *
     * @param token  {@link String}
     * @param object {@link Object}
     */
    public static void sendInfoObject(String token, Object object) {
        try {
            if (WebSocketServer.getSessionPool().containsKey(token)) {
                Session session = WebSocketServer.getSessionPool().get(token);
                WebSocketUtil.sendMessageObject(session, object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
